package com.gdit.zax.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.PlanDao;
import com.gdit.zax.dao.SectionDao;
import com.gdit.zax.entitys.Section;
import com.gdit.zax.entitys.TaskAll;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.O;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.VeriFicUtil;
import com.gdit.zax.utils.webUtil;

public class GetTaskToday extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String accesstoken = request.getParameter("accesstoken");
		
		//检测参数
		if (TextUtil.isEmpty(accesstoken)) {
			O.printFail(response, 1, "请检查accesstoken参数!");
			return;
		}
		
		
		//检测连接、用户
		int uid = VeriFicUtil.getVFID(accesstoken);
		Connection conn = DBUtil.getConnection();
		
		if (uid==Integer.MIN_VALUE || uid==Integer.MAX_VALUE) {
			O.printNoLogin(response);
			return;
		}
		
		if (conn==null) {
			O.printFail(response, 1000, "数据库连接失败!");
			return;
		}
		
		//开始
		DAOFactory dao  = DAOFactory.init(conn, request, response);
		PlanDao pdao = dao.getPlanDao();
		SectionDao sdao = dao.getSectionDao();
		ArrayList<TaskAll> list  = pdao.listTask(uid, 1, 1000);
		
		Map<String, Object> out = new HashMap<String,Object>();
		
		ArrayList<Map<String, Object>> todaytask = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < list.size(); i++) {
			TaskAll task = list.get(i);
			if (i==0) {
				out.put("starttime", task.getT_plan_addtime());
				out.put("countdown", task.get_countdown());
				out.put("progress", task.get_progress());

				Section section = sdao.getSectionInfo(task.getT_seerecord_sectionid());
				if (section==null) {
					out.put("state","未开始");
				} else {
					out.put("state","已进行到" + section.getName());
				}
				
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("pic", webUtil.getWebAbsoluteUrl(task.getT_video_pic(), Constant.PIC_video) );
				map.put("name", task.getT_course_name());
				map.put("progress", task.get_progress());
				
				Section section = sdao.getSectionInfo(task.getT_seerecord_sectionid());
				if (section==null) {
					map.put("state","未开始");
				} else {
					map.put("state","已进行到" + section.getName());
				}
				
				todaytask.add(map);
			}
		}
		out.put("todaytask", todaytask);
		O.printSuccess(response, out);
		
		
	}

}
